#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include "PahoMqttClient.h"
#include "thmar_types.h"
#include "local_error.h"
#include "c11code.h"

#define ADDRESS     "tcp://localhost:1883"
#define CLIENTID    "ExampleClientPub"
#define TOPIC       "test_paho"
#define USERNAME    "user"
#define PASSWORD    "password"
#define PAYLOAD     "Hello World!"

using namespace smq;
ThmarMqttClient* client;
// 定义在程序退出时执行的函数
void cleanup() {
    printf("Program exiting, cleaning up...\n");
    if(client)
    {
        printf("Stopping client...\n");
        client->stop();
        delete client;
        client = NULL;
    }
}
// 自定义的信号处理函数
void handle_sigint(int sig) {
    printf("Catch Ctrl-C, exit program.\n");
    exit(0);
}

int main(int argc, char* argv[])
{
    // 注册退出时执行的函数
    if (atexit(cleanup) != 0) {
        fprintf(stderr,"failed to register cleanup function, exiting...\n");
        exit(1);
    }
    // 设置信号处理器
    signal(SIGINT, handle_sigint);
    client = new PahoMqttClient(ADDRESS, USERNAME, PASSWORD,CLIENTID);
    printf("PahoMqttClient created\n");
    printf("Connecting to server...\n");
    int code = client->start();
    if(code){
        printf("Connect failed with code %d\n", code);
        // 输出paho mqtt错误信息
        thmar_print_local_err();
    }else{
        printf("Connect success\n");
    }
    printf("Publishing to topic %s for client %s\n\n", TOPIC, CLIENTID);
    char payload[100];
    for (int i = 0; i < 100; i++)
    {
        snprintf(payload, sizeof(payload), "Hello, world! %d", i);
        int code = client->publish(TOPIC, payload);
        if(code){
            printf("Publish failed with code %d\n", code);
            // 输出paho mqtt错误信息
            thmar_print_local_err();
            break;
        }else{
            printf("Publish success %s\n", payload);
        }
        // thmar_sleep_ms(2000); // wait for all retained messages to arrive
    }
    return 0;
}



